const fs=require("fs");
const paths=require("../config/paths");
const path=require("path");
function filesFinder(){
     return new Promise((resolve)=>{
         fs.readdir(paths.components,(err,files)=>{
             if (err){
                 throw err;
             }
             resolve(files);
         })
     })
}
function readFile(path=paths.tsconfig){
     return new Promise((resolve)=>{
           fs.readFile(path,(err,data)=>{
                if (err){
                    throw err;
                }
                const str=data.toString();
                resolve(JSON.parse(str));
           })
     })
}
function writeTsConfig(filePath){
     return new Promise(async (resolve)=>{
          const tsConfig=await readFile();
         tsConfig.include=[path.join(paths.components,filePath), "./src/cssType/index.d.ts"];
          fs.writeFile(paths.tsconfig,JSON.stringify(tsConfig,"","\t"),(err)=>{
               if (err){
                   throw err
               }
               resolve();
          })
     })
}//改写tsconfig文件打包时候排除不需要.d文件编译
function checkFiles(filePath){
    return new Promise((resolve)=>{
        fs.stat(filePath, (statErr, data)=>{
            if (statErr){
                throw  statErr;
            }
            if (data.isDirectory()){
                resolve({dir:filePath});
            }else if (data.isFile()){
                resolve({file:filePath});
            }
        });
    })
}//检查是文件还是文件夹
function eachFiles(filesList){
      return new Promise(async (resolve)=>{
          const filesFindArray=[]
          const files=[];
          filesList.forEach((item)=>{
              const {dir,file}=item;
              if (dir){
                  filesFindArray.push(findPathFiles(dir));
              }else if (file){
                  files.push(file);
              }
          })
          const result=await Promise.all(filesFindArray);
          result.forEach((item)=>{
              files.push(...item);
          })
          resolve(files);
      })
}//遍历是文件还是文件夹
function findPathFiles(filePath){
     return new Promise(async (resolve)=>{
           let filesArray=[];
           fs.readdir(filePath,async (err,files)=>{
                 if (err){
                     throw err;
                 }
                 const filesFindArray=[];
                 files.forEach((item)=>{
                     const itemPath=path.join(filePath,item);
                      filesFindArray.push(checkFiles(itemPath));
                 })
               let filesPathResult;
               if (filesFindArray.length){
                   filesPathResult=await Promise.all(filesFindArray);
                   filesArray=await eachFiles(filesPathResult);
               }
               resolve(filesArray);
           })
     })
}//获取路径下所有文件

exports.findPathFiles=findPathFiles;

exports.filesFinder=filesFinder;

exports.writeTsConfig=writeTsConfig;

exports.readFile=readFile;


